#include "mainwindow.h"
#include"base.h"
#include<QIcon>
#include<QPainter>
#include<QObject>
#include"start.h"
#include<QTimer>
#include "myplane.h"
#include"bullet.h"
#include"enemyplane.h"
#include <ctime>
#include <QSoundEffect>
MainScene::MainScene(QWidget *parent)
    : QWidget(parent)
{
    initScene();
    game.show();
    connect(&game,SIGNAL(startsignal()),this,SLOT(playGame()));

}

void MainScene::initScene()
{
    //初始化窗口大小
    setFixedSize(GAME_WIDTH,GAME_HEIGHT);
    //设置窗口标题
    setWindowTitle(GAME_TITLE);
    setWindowIcon(QIcon( GAME_ICON));
    score=0;
    m_Timer.setInterval(GAME_RATE);
    m_recorder = 0;
    item_recorder=0;
    bullet_recorder=0;
    m_hero.protectrecoder=0;
    unlimited=false;
    //随机数种子
    srand((unsigned int)time(NULL));
}
void MainScene::updatePosition()
{
    //更新地图坐标
    m_map.mapPosition();
    //发射子弹
        m_hero.shoot();
        //计算子弹坐标
        for(int i = 0 ;i < BULLET_NUM;i++)
        {
            //如果子弹状态为非空闲，计算发射位置
            if(!m_hero.m_bullets[i].bullet_Free)
            {
                m_hero.m_bullets[i].updatePosition();
            }
            if(unlimited)
            {
                if( m_hero.m_bullets[i].bullet_Y<=-36)
                {
                    m_hero.m_bullets[i].bullet_Free=true;
                }
            }
        }
        //敌机坐标计算
        for(int i = 0 ; i< ENEMY_NUM;i++)
        {
            //非空闲敌机 更新坐标
            if(m_enemys[i].m_Free == false)
            {
                m_enemys[i].updatePosition();
            }
        }
        //更新道具坐标
         for(int i = 0 ; i< ENEMY_NUM;i++)
        {
             if(items[i].m_Free == false)
      { items[i].updatePosition();}
         }
        //计算爆炸播放的图片
        for(int i = 0 ; i < BOMB_NUM;i++)
        {
            if(m_bombs[i].m_Free == false)
            {
                     m_bombs[i].updateInfo();
            }
        }
}
void MainScene::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    QPainter paintershiled(this);
    //绘制地图
    painter.drawPixmap(0,m_map.m_map1_posY , m_map.m_map1);
    painter.drawPixmap(0,m_map.m_map2_posY , m_map.m_map2);
    //绘制保护框
    if(!m_hero.Underprotecttime())
    {painter.drawPixmap(m_hero.m_X,m_hero.m_Y,m_hero.m_Plane);}
    else
      {painter.drawPixmap(m_hero.m_X,m_hero.m_Y,m_hero.m_Planepro);}
    //绘制护盾
    for(int i=0;i<m_hero.Shields;i++)
    {
        painter.drawPixmap(i*50,720,m_map.shield1);
    }
    //绘制空血框
    for(int i=m_hero.Shields;i<m_hero.Shields_max;i++)
    {
        painter.drawPixmap(i*50,720,m_map.shield2);
    }
    QFont scorefont1("宋体",15,QFont::Bold,true);
    QFont scorefont2("宋体",10,QFont::Bold,true);
    scorefont1.setLetterSpacing(QFont::AbsoluteSpacing,10);
    painter.setFont(scorefont1);
    painter.setPen(Qt::yellow);
    painter.drawText(50,50,"得分"+QString::number(score));
    paintershiled.setFont(scorefont2);
    paintershiled.setPen(Qt::blue);
    paintershiled.drawText(0,700,"剩余血量"+QString::number(m_hero.Shields));
    //绘制子弹
        for(int i = 0 ;i < BULLET_NUM;i++)
        {
            //如果子弹状态为非空闲，计算发射位置
            if(!m_hero.m_bullets[i].bullet_Free)
            {
                painter.drawPixmap(m_hero.m_bullets[i].bullet_X,m_hero.m_bullets[i].bullet_Y,m_hero.m_bullets[i].my_Bullet);
            }
    }
        for(int i=0;i<BULLET_NUM;i++)
        {
            if(!m_hero.m_bullets[i].bullet_Free&&m_hero.m_bullets[i].bullet_Y<=-35)
                {
               bullet_recorder++;
            }
        }
        if(bullet_recorder==BULLET_NUM)
        {
            gameover();
        }
        else
        {
            bullet_recorder=0;
        }
        //绘制敌机
        for(int i = 0 ; i< ENEMY_NUM;i++)
        {
            if(m_enemys[i].m_Free == false)
            {
                painter.drawPixmap(m_enemys[i].m_X,m_enemys[i].m_Y,m_enemys[i].m_enemy);
            }
        }
        //绘制道具
        for(int i = 0 ; i< ENEMY_NUM;i++)
        {
            if(items[i].m_Free == false)
        {painter.drawPixmap(items[i].m_X,items[i].m_Y,items[i].m_item);}
        }
        //绘制爆炸图片
        for(int i = 0 ; i < BOMB_NUM;i++)
        {
            if(m_bombs[i].m_Free == false)
           {        painter.drawPixmap(m_bombs[i].m_X,m_bombs[i].m_Y,m_bombs[i].m_pixArr[m_bombs[i].m_index]);
            }
        }
}
void MainScene::playGame()
{
    //启动背景音乐
        //QSoundEffect::play(SOUND_BACKGROUND)
        QSoundEffect * startSound = new QSoundEffect(this);
        startSound->setSource(QUrl::fromLocalFile("://res/Hillsong-Young-_-Free-Wake-_Live_-_1_.wav"));
        startSound->play();
        this->show();
    //启动定时器
    m_Timer.start();
    connect(&m_Timer,
            &QTimer::timeout,
            [=](){
        //敌机出场
           enemyToScene();
           //道具出场
           Itemtoscence();
            //更新游戏中元素的坐标
                  updatePosition();
                  update();
                  collisionDetection();//碰撞检测
                  planeclocollisionDetection();
                   itemclocollisionDetection();
                 }
           );
}

void MainScene::mouseMoveEvent(QMouseEvent* event)
{
    int x = event->x() - m_hero.m_Rect.width()*0.5;     //鼠标位置
    int y = event->y() - m_hero.m_Rect.height()*0.5;

     //边界检测
    if(x <= 0 )
{
    x = 0;
}
if(x >= GAME_WIDTH - m_hero.m_Rect.width())
{
    x = GAME_WIDTH - m_hero.m_Rect.width();
}
if(y <= 0)
{
    y = 0;
}
if(y >= GAME_HEIGHT - m_hero.m_Rect.height())
{
    y = GAME_HEIGHT - m_hero.m_Rect.height();
}
m_hero.setPosition(x,y);
}

void MainScene::keyPressEvent(QKeyEvent *e)
{
        switch(e->key()){
        case Qt::Key_W :{
            if(m_hero.m_Y>m_hero.m_Rect.height()){
                m_hero.m_Y-=25;
            }
            break;
        }
        case Qt::Key_S:{
            if(m_hero.m_Y<GAME_HEIGHT-m_hero.m_Rect.height()){
                m_hero.m_Y+=25;

            }
            break;
        }
        case Qt::Key_A:{
            if(m_hero.m_X>m_hero.m_Rect.width()){
               m_hero.m_X-=25;

            }
            break;
        }
        case Qt::Key_D:{
            if(m_hero.m_X<GAME_WIDTH-m_hero.m_Rect.width()){
                m_hero.m_X+=25;

                }
             break;
        case Qt::Key_L:{
                if(m_Timer.isActive())
                m_Timer.stop();
                else
                m_Timer.start();
                break;
            }
            }
        }

        }


void MainScene::enemyToScene()
{
    m_recorder++;
    if(m_recorder < ENEMY_INTERVAL)
    {
        return;
    }
    m_recorder = 0;
for(int i = 0 ; i< ENEMY_NUM;i++)
{
    if(m_enemys[i].m_Free)
    {
        //敌机空闲状态改为false
        m_enemys[i].m_Free = false;
        //设置坐标
        m_enemys[i].m_X = rand() % (GAME_WIDTH - m_enemys[i].m_Rect.width());
        m_enemys[i].m_Y = -m_enemys[i].m_Rect.height();
        break;
    }
  }
}
void MainScene::collisionDetection()
{
    //遍历所有非空闲的敌机
    for(int i = 0 ;i < ENEMY_NUM;i++)
    {
        if(m_enemys[i].m_Free)
        {
            //空闲飞机跳转下一次循环
            continue;
        }
        //遍历所有非空闲的子弹
        for(int j = 0 ; j < BULLET_NUM;j++)
    {
        if(m_hero.m_bullets[j].bullet_Free)
        {
           //空闲子弹 跳转下一次循环
            continue;
        }
        //如果子弹矩形框和敌机矩形框相交，发生碰撞，同时变为空闲状态即可
        if(m_enemys[i].m_Rect.intersects(m_hero.m_bullets[j].bullet_Rect))
        {
            QSoundEffect * startSound = new QSoundEffect(this);
                           startSound->setSource(QUrl::fromLocalFile(":/n/res/bomb.wav"));
                           startSound->play();
            score++;
            m_hero.m_bullets[j].bullet_Free = true;
            m_enemys[i].m_shields--;
            if(m_enemys[i].m_shields<=0)
           {
                m_enemys[i].m_Free = true;
                m_enemys[i].reload();
            for(int k = 0 ; k < BOMB_NUM;k++)
            { if(m_bombs[k].m_Free)
                {
                    //爆炸状态设置为非空闲
                    m_bombs[k].m_Free = false;
                    //更新坐标
                                m_bombs[k].m_X = m_enemys[i].m_X;
                                m_bombs[k].m_Y = m_enemys[i].m_Y;
                                break;
                  }
            }
            }
        }
    }

  }
}
void MainScene::planeclocollisionDetection()
{
    //遍历所有非空闲的敌机
    for(int i = 0 ;i < ENEMY_NUM;i++)
    {
        if(m_enemys[i].m_Free)
        {
            //空闲飞机跳转下一次循环
            continue;
        }
        if(m_enemys[i].m_Rect.intersects(m_hero.m_Rect))
        {
            if(!m_hero.Underprotecttime())
            {
                m_hero.Shields--;
                m_hero.protectrecoder=0;
            }
        }
    }
    if(m_hero.Shields==0)
    {
        gameover();
        m_hero.protectrecoder=30;
    }
}
void MainScene::Itemtoscence()
{
    item_recorder++;
    if(item_recorder < ITEM_INTERVAL)
    {
        return;
    }
    item_recorder = 0;
    for(int i = 0 ;i < ENEMY_NUM;i++)
    {
        if(items[i].m_Free)
       {
        //道具空闲状态改为false
        items[i].m_Free = false;
        //设置坐标
        items[i].m_X = rand() % (GAME_WIDTH - items[i].m_Rect.width());
        items[i].m_Y = -items[i].m_Rect.height();
        break;
        }
    }
}
void MainScene::itemclocollisionDetection()
{

    for(int i = 0 ;i < ENEMY_NUM;i++)
    {
        if(items[i].m_Free)
        {
            //空闲道具跳转下一次循环
            continue;
        }
        if(items[i].m_Rect.intersects(m_hero.m_Rect))
        {
            items[i].m_Free=true;
            switch(items[i].item_code)
             {
            case 1:
                if(m_hero.Shields<m_hero.Shields_max)
                {m_hero.Shields++;}
                break;
            case 2:
                m_hero.Shields_max++;
                break;
            default:
                m_hero.protectrecoder=-100;
                break;
              }
            items[i].reload();
        }

}
}
void MainScene::gameover()
{
    emit gameoversignal();
}
void MainScene::bulletunlimited()
{
unlimited=true;
}
void MainScene::intervalfastslot()
{
    m_hero.bullet_interval=30;
}
void MainScene::intervalmidslot()
{
    m_hero.bullet_interval=40;
}
void  MainScene::bulletspeedfastslot()
{
    for(int i = 0 ;i < BULLET_NUM;i++)
    {

        m_hero.m_bullets[i].bullet_Speed=10;
    }
}
void  MainScene::heroplaneshieldslowslot()
{
    m_hero.Shields=3;
    m_hero.Shields_max=3;
}
void  MainScene::heroplaneshieldshighslot()
{
    m_hero.Shields=8;
    m_hero.Shields_max=8;
}
void  MainScene::mountainmapchangeslot()
{
    m_map.m_map1.load(":/n/res/img_bg_level_1.jpg");
    m_map.m_map2.load(":/n/res/img_bg_level_1.jpg");
}
void  MainScene::skymapchangeslot()
{
    m_map.m_map1.load(":/n/res/img_bg_level_2.jpg");
    m_map.m_map2.load(":/n/res/img_bg_level_2.jpg");
}
void  MainScene::desertmapchangeslot()
{
    m_map.m_map1.load(":/n/res/img_bg_level_3.jpg");
    m_map.m_map2.load(":/n/res/img_bg_level_3.jpg");
}
void  MainScene::firemapchangeslot()
{
    m_map.m_map1.load(":/n/res/img_bg_level_5.jpg");
    m_map.m_map2.load(":/n/res/img_bg_level_5.jpg");
}
